package com.bookmngsys.dao;

import com.bookmngsys.entity.BorrowHistory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

public interface BorrowHistoryDao extends JpaRepository<BorrowHistory, String> {
    @Query(value = "select * from borrow_history", nativeQuery = true)
    ArrayList<BorrowHistory> getAllBorrowHistory();

    @Query(value = "select * from borrow_history where reader_id = :readerId", nativeQuery = true)
    ArrayList<BorrowHistory> getAllBorrowHistoryByReaderId(Integer readerId);

    @Query(value = "select * from borrow_history where isbn = :isbn and book_id = :bookId and reader_id = :readerId and borrow_date = :borrowDate and return_date = :returnDate and is_returned = false", nativeQuery = true)
    BorrowHistory findValidBorrowHistory(String isbn, Integer bookId, Integer readerId, Long borrowDate, Long returnDate);

    @Transactional
    @Modifying
    @Query(value = "UPDATE borrow_history SET is_returned = true where book_id  = :bookId and (is_retruned is null or is_returned = false) and return_date >= :curTime", nativeQuery = true)
    void setIsReturned(Integer bookId, Long curTime);


}
